/**
 * 易驰护运 - UploadPic
 * http://menger.me
 * @桓桓
 */

'use strict';

import React from 'react'
import {ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import {LargePicture} from '../../components'
import {Geolocation, MapApp} from 'react-native-baidu-map'
import {inject, observer} from 'mobx-react'
import {Predefine} from '../../config/predefine'

@inject('loginStore')
@observer
export default class UploadPic extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            weight: '',
            weight_img: [],

            warp: '',
            weft: '',
            address: '',
        }
    }

    componentDidMount() {
        this.getCurrentPosition();
    }

    getCurrentPosition = () => {
        Geolocation.getCurrentPosition()
            .then(data => {
                console.log(data)
                this.setState({
                    warp: data.longitude,
                    weft: data.latitude,
                    address: data.address
                })
            })
            .catch(e => {
                console.warn(e, 'error');
            })
    }

    _onSelectedPhotos = async () => {
        let _result = await MediaManager.showPicker({
            type: 'camera',
            // includeBase64: true,
        });
        if (_result && _result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.loading('上传中...', {duration: 9999999});
            const upRes = await Services.uploadQiNiu(_result.data);
            if (upRes.code === StatusCode.SUCCESS_CODE) {
                ToastManager.hide();
                // ToastManager.success('上传成功');
                // this.setState({weight_img: ServicesApi.QI_NIU_HOST + upRes.data[0].key});
                let images = [];
                upRes.data.map((item, index) => {
                    images.push(ServicesApi.QI_NIU_HOST + item.key);
                })
                let {weight_img} = this.state;
                let newImage = images.concat(weight_img);
                this.setState({weight_img: newImage});
            } else {
                ToastManager.fail('上传失败');
            }
        }
    };

    // 删除照片
    deleteImg = (index) => {
        let {weight_img} = this.state;
        let _imgs = weight_img.slice();
        _imgs.splice(index, 1);
        this.setState({weight_img: _imgs})
    }
    
    onSubmit = async () => {
        let {item, type, onRefresh} = this.params;
        let {weight, weight_img, warp, weft} = this.state;
        if (weight == '') {
            ToastManager.message('请上传货物吨数')
            return
        }
        if (weight_img == '') {
            ToastManager.message('请上传单据')
            return
        }
        let url = ServicesApi.VEHICLE_ORDER_OPERATE;
        let data = {
            id: item.id,
            type: type, 
            weight,
            weight_img: weight_img.join('|'),
            warp: warp,
            weft: weft,
        }
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.success(result.msg);
            onRefresh && onRefresh()
            RouterHelper.goBack()
        } else {
            ToastManager.fail(result.msg);
        }
    }

    upImgView = (data) => {
        let contain = data.map((item, index) => {
            return (
                <View key={index} style={styles.upImgItem}>
                    <LargePicture
                        resizeMode={'cover'}
                        style={styles.upImgItemImg}
                        imageStyle={styles.upImgItemImg}
                        source={{uri: item}}
                    />
                    <Text style={styles.upImgItemText}>点击查看</Text>
                    <TouchableOpacity style={styles.deleteBox} onPress={() => this.deleteImg(index)}>
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.delete}
                            source={Images.icon_result_fail}
                        />
                    </TouchableOpacity>
                </View>
            )
        })
        return (
            <ScrollView
                style={styles.upImgBox}
                horizontal={true}
                showsHorizontalScrollIndicator={false}
            >
                {
                    data.length < 3 &&
                    <TouchableOpacity style={styles.upImgItem} onPress={() => this._onSelectedPhotos()}>
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.upImgItemImg}
                            source={Images.icon_up_img}
                        />
                        <Text style={styles.upImgItemText}>立即上传</Text>
                    </TouchableOpacity>
                }
                {contain}
            </ScrollView>
        )
    }

    render() {
        let {weight, weight_img} = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar
                    title={'单据上传'}
                    style={[styles.navigationBarStyle]}
                />
                <View style={styles.line1}>
                    <Text style={styles.lineLeft} numberOfLines={1}>货物吨数：</Text>
                    <TextInput
                        defaultValue={weight}
                        style={styles.lineInput}
                        keyboardType={'phone-pad'}
                        placeholder={'请输入'}
                        placeholderTextColor={'#999'}
                        onChangeText={(text) => this.setState({weight: text})}
                    />
                </View>
                <TouchableOpacity style={styles.line2} onPress={this._onSelectedPhotos}>
                    <Text style={styles.lineLeft} numberOfLines={1}>上传单据：</Text>
                    {this.upImgView(weight_img)}
                </TouchableOpacity>
                <View style={styles.btnBox}>
                    <Button
                        style={styles.btn}
                        title={'上传'}
                        titleStyle={styles.btnTitle}
                        resizeMode={'cover'}
                        backgroundImage={Images.img_btn_bg1}
                        onPress={() => this.onSubmit()}
                    />
                </View>

            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#fff',
    },
    line1: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginHorizontal: 15,
        paddingVertical: 15,
        borderBottomWidth: Predefine.minPixel,
        borderBottomColor: '#e1e1e1',
    },
    lineLeft: {
        color: '#333',
        fontSize: 14,
    },
    lineInput: {
        flex: 1,
        fontSize: 14,
        textAlign: 'right',
    },
    line2: {
        marginHorizontal: 15,
        paddingVertical: 15,
        borderBottomWidth: Predefine.minPixel,
        borderBottomColor: '#e1e1e1',
    },

    upImgBox: {
        height: 100,
        marginVertical: 15,
        marginHorizontal: 5,
        borderRadius: 5,
        backgroundColor: '#F6F7FD',
        paddingLeft: 10,
    },
    upImgItem: {
        alignItems: 'center',
        marginRight: 20,
        height: 100,
        alignItems: 'center',
        justifyContent: 'center',
    },
    upImgItemImg: {
        width: 60,
        height: 60,
        borderRadius: 1,
    },
    upImgItemText: {
        fontSize: 13,
        color: '#999',
        marginTop: 6,
    },
    deleteBox: {
        position: 'absolute',
        right: -8,
        top: 2,
        width: 16,
        height: 16,
    },
    delete: {
        width: 16,
        height: 16,
    },

    btnBox: {
        padding: 15,
    },
    btn: {
        backgroundColor: DominantColor,
    },
});